/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/* 
 * Copyright (c) 2009 City University of Hong Kong
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License m_version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * Author: Wilson Thong (wilsonwk@ee.cityu.edu.hk) 
 */
#include "jitter-sim-include.h"
#include "unicast-session-helper.h"
#include "ns3/inet-socket-address.h"
#include "ns3/udp-echo-client.h"

NS_LOG_COMPONENT_DEFINE ("UnicastSessionHelper");

namespace ns3 {
namespace eecityu {

UnicastSessionHelper::UnicastSessionHelper(void) :
  // the default remote host address is set to GetAny (), which is 
  // an incorrect value. Before installing a source onto a node,
  // this remote host address must be reset to a correct value
  // by modifying the "RemoteAddress" attribute of the UdpEchoClient class
  m_sourceHelper (Ipv4Address::GetAny (), BASE_UDP_PORT),
  m_destinationHelper ("ns3::UdpSocketFactory", InetSocketAddress (BASE_UDP_PORT))
{
  // set the typeid so that 'm_monitorFactory' can create 
  // UnicastSessionMonitor objects
  m_monitorFactory.SetTypeId ("ns3::eecityu::UnicastSessionMonitor");
}

DataRate 
UnicastSessionHelper::GetSourceDataRate (Ptr<Application> src)
{
  // get the packet size (in bytes) generated from the node
  UintegerValue pkgSizeValue;
  src->GetAttribute ("PacketSize", pkgSizeValue);
  uint32_t pkgSize = pkgSizeValue.Get ();
  // get the intger-packet interval for the packets generated from the source node
  TimeValue interPkgTimeValue;
  src->GetAttribute ("Interval", interPkgTimeValue);
  double interPkgTime = interPkgTimeValue.Get ().GetSeconds ();
  // calculate the data rate and return it
  DataRate dr ( (uint64_t) (pkgSize*8 / interPkgTime) );
  return dr;
}

Ptr<UnicastSessionMonitor>
UnicastSessionHelper::CreateMonitor (Ptr<Application> src, Ptr<Application> dst)
{
  NS_LOG_FUNCTION (src->GetNode ()->GetId () << dst->GetNode ()->GetId ());

  m_monitorFactory.Set ("SourceApplication", PointerValue (src));
  m_monitorFactory.Set ("SinkApplication", PointerValue (dst));
  Ptr<UnicastSessionMonitor> mon = m_monitorFactory.Create<UnicastSessionMonitor> ();

  NS_LOG_LOGIC ("Monitor session = " << mon->GetSessionIndex () 
    << ", source node = " << mon->GetSource ()->GetId () 
    << ", destination = " << mon->GetDestination ()->GetId ());
  
  return mon;
}

//ApplicationContainer 
//UnicastSessionHelper::InstallSession (Ptr<Node> src, Ptr<Node> dst)
//{
//  NS_LOG_FUNCTION (src << dst);
//
//  // install the sourcing and sinking applications onto the src node and dst node
//  ApplicationContainer appCon = InstallSessionWithTraceSource (src, dst);
//  // connect a callback to all the net devices on this node to handle the 
//  // packet sent events
//  std::ostringstream oss;
//  oss << "/NodeList/" << src->GetId () << "/DeviceList/*/$ns3::PointToPointNetDevice/TxQueue/Dequeue";
//  Config::ConnectWithoutContext (
//    oss.str (), 
//    MakeBoundCallback (&UnicastSessionHelper::HandlePacketSentEvent, src)
//    );
//  // clear the contain of the oss
//  oss.str ("");
//  // connect a callback to all the net devices on this node to handle the
//  // packet received event
//  oss << "/NodeList/" << dst->GetId () << "/DeviceList/*/$ns3::PointToPointNetDevice/MacRx";
//  Config::ConnectWithoutContext (
//    oss.str (), 
//    MakeBoundCallback (&UnicastSessionHelper::HandlePacketReceivedEvent, dst)
//    );
//
//  return appCon;
//}

ApplicationContainer 
UnicastSessionHelper::InstallSession (Ptr<Node> src, Ptr<Node> dst)
{
  NS_LOG_FUNCTION (src << dst);

  // get the destination IPv4 address
  Ptr<Ipv4> dstIpv4 = dst->GetObject<Ipv4> ();
  Ipv4Address dstAddr = dstIpv4->GetAddress (1, 0).GetLocal ();
  // install the traffic source and traffic sink onto the source node and destination node.
  // Return an ApplicationContainer containing the traffic source and traffic sink
  ApplicationContainer app;
  // set the destination address to the traffic source helper
  m_sourceHelper.SetAttribute ("RemoteAddress", Ipv4AddressValue (dstAddr));
  // set the UDP port for the source and the destination of this unicast session
  m_sourceHelper.SetAttribute (
    "RemotePort", UintegerValue (BASE_UDP_PORT + dst->GetNApplications ()));
  m_destinationHelper.SetAttribute (
    "Local", AddressValue (InetSocketAddress (BASE_UDP_PORT + dst->GetNApplications ())));
  // Install the application to the source node and destination node respectively
  m_lastAllocatedSourceApplication = m_sourceHelper.Install (src).Get (0);
  NS_LOG_LOGIC ("Number of applications installed on source node-" 
    << src->GetId () << " in total = " << src->GetNApplications ());
  m_lastAllocatedSinkApplication   = m_destinationHelper.Install (dst).Get (0);
  NS_LOG_LOGIC ("Number of applications installed on destination node-" 
    << dst->GetId () << " in total = " << dst->GetNApplications ());
  app.Add (m_lastAllocatedSourceApplication);
  app.Add (m_lastAllocatedSinkApplication);
  NS_LOG_LOGIC ("Allocated traffic session from source node = " << src->GetId () 
    << " to destination = " << dst->GetId ());
  return app;
}

const Ptr<Application> 
UnicastSessionHelper::GetLastAllocatedSourceApplication () const
{
  NS_LOG_FUNCTION_NOARGS ();

  return m_lastAllocatedSourceApplication;
}

const Ptr<Application> 
UnicastSessionHelper::GetLastAllocatedSinkApplication () const
{
  NS_LOG_FUNCTION_NOARGS ();

  return m_lastAllocatedSinkApplication;
}

void 
UnicastSessionHelper::SetDestinationAttribute (std::string name, const AttributeValue &value)
{
  m_destinationHelper.SetAttribute (name, value);
}

void 
UnicastSessionHelper::SetSourceAttribute (std::string name, const AttributeValue &value)
{
  m_sourceHelper.SetAttribute (name, value);
}

} // namespace eecityu
} // namespace ns3
